<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" width="650px" @ok="handleSubmit" showFooter destroyOnClose>
    <BasicForm @register="registerForm">
      <template #bindMchStatus="{ model, field }">
        <a-form-item-rest>
          <span class="ml-2">{{ model[field] ? "已绑定" : "未绑定" }}</span>
          <a-button class="ml-4" type="primary" size="middle" @click="handleOpenBind(model, field)">
            {{ model[field] ? "重新绑定" : "去绑定" }}
          </a-button>
        </a-form-item-rest>
      </template>
    </BasicForm>
  </BasicDrawer>
  <SelectMch @register="registerSelectMch" @success="handleSelectMchSuccess" />
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { bindFormSchema } from "../qrcode.data"
  import * as api from "/@/api/pay"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { useModal } from "/@/components/Modal"
  import SelectMch from "./SelectMch.vue"

  const { createMessage } = useMessage()
  const emit = defineEmits(["register", "success"])
  const title = ref("绑定管理")
  const record = ref<any>({})
  const [registerSelectMch, { openModal: openSelectMch }] = useModal()
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: "80px",
    schemas: bindFormSchema,
    showActionButtonGroup: false,
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      record.value = await api.getMchQrcode({ id: data.record.id })
      await setFieldsValue({ ...record.value })
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  async function handleSubmit(v) {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })
      await api.mchQrcodeBindMch({ ...values })
      closeDrawer()
      emit("success")
      createMessage.success(`绑定成功`)
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const handleOpenBind = (model, field) => {
    openSelectMch(true, { record })
  }

  const handleSelectMchSuccess = async (data) => {
    console.log("selectInfo: ", data)
    await setFieldsValue({ ...data })
  }
</script>
